package com.hundsun.epay.autosimu.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.hundsun.epay.autosimu.api.GeneratedJavaFile;
import com.hundsun.epay.autosimu.api.IntrospectedChannel;
import com.hundsun.epay.autosimu.api.PayCorporationIntrospector;
import com.hundsun.epay.autosimu.enums.CommunicationMethod;
import com.hundsun.epay.autosimu.utils.StringUtility;

public class PayCorporation {
	private String id;
//	private String className;
	private CommunicationMethod commMethod;
	private String packageName;
	private List<Channel> channels;
	
	public PayCorporation() {
		super();
		channels = new ArrayList<Channel>();
	}
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
//	public String getClassName() {
//		return className;
//	}
//	public void setClassName(String className) {
//		this.className = className;
//	}
	public CommunicationMethod getCommMethod() {
		return commMethod;
	}
	public void setCommMethod(CommunicationMethod commMethod) {
		this.commMethod = commMethod;
	}
	public String getPackageName() {
		return packageName;
	}

	public void setPackageName(String packageName) {
		this.packageName = packageName;
	}

	public List<Channel> getChannels(){
		return channels;
	}
	public void addChanel(Channel channel){
		channels.add(channel);
	}
	
	public Channel getChannel(String id){
		for (Channel channel : channels) {
			if(id.equals(channel.getId())){
				return channel;
			}
		}
		return null;
	}
	
	public void validate(List<String> errors){
		if(!StringUtility.stringHasValue(id)){
			errors.add("\"id\" is required in a context");
		}
		
		for (Channel channel : channels) {
			channel.validate(errors, commMethod != null);
		}
	}
	
	private List<IntrospectedChannel> introspectedChannels;
	
	public void introspectChannel(Set<String> channelIds, Set<String> tradeIds){
		introspectedChannels = new ArrayList<IntrospectedChannel>();
		PayCorporationIntrospector payCorpIntrospector = new PayCorporationIntrospector(this);
		for (Channel channel : channels) {
			if(channelIds != null && channelIds.size() > 0 && !channelIds.contains(channel.getId())){
				continue;
			}
			List<IntrospectedChannel> channels = payCorpIntrospector.introspectChannels(channel, tradeIds);
			if(!channels.isEmpty()){
				introspectedChannels.addAll(channels);
			}
		}
	}
	
	public void generateFiles(List<GeneratedJavaFile> javaFiles, List<String> wrannings){
		if(introspectedChannels != null){
			for (IntrospectedChannel introspectedChannel : introspectedChannels) {
				//初始化通道配置
				introspectedChannel.initialize();
				//初始化并执行生成器
				introspectedChannel.initGenerators(wrannings);
				//生成的java文件
				javaFiles.addAll(introspectedChannel.getGenerateJavaFiles());
			}
		}
	}
}
